package com.ruoyi.common.utils.aliPay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


/**
 * @author ywh
 * @date 2020/12/17
 * @desc
 */
public class AlipayUtil {

    private static AlipayClient client=AlipayConfig.getAlipayClient();
    /***
     * 支付
     * @param price
     * 产品销售码
     * 1.电脑网站支付产品alipay.trade.page.pay接口中，product_code为：FAST_INSTANT_TRADE_PAY
     * 2.手机网站支付产品alipay.trade.wap.pay接口中，product_code为：QUICK_WAP_WAY
     * 3.当面付条码支付产品alipay.trade.pay接口中，product_code为：FACE_TO_FACE_PAYMENT
     * 4.APP支付产品alipay.trade.app.pay接口中，product_code为：QUICK_MSECURITY_PAY
     * @param orderNum
     * @return
     * @throws AlipayApiException
     */
    public static Map<String,Object> getAliPayResult(BigDecimal price, String orderNum,String notifyUrl)  {
        //1、获得初始化的AlipayClient
        //2、设置请求参数
        AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest ();
        //页面跳转同步通知页面路径
        alipayRequest.setReturnUrl("");
        // 服务器异步通知回调逻辑
        alipayRequest.setNotifyUrl(notifyUrl);
        //封装参数
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setOutTradeNo(orderNum);
        model.setSubject("在线支付");  // 订单标题
        model.setTotalAmount(price.toString());
        model.setProductCode("QUICK_MSECURITY_PAY");//销售码
        model.setTimeoutExpress("30m");
        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号) 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
       //model.setSellerId(AlipayConfig.PID);
        alipayRequest.setBizModel(model);
        try {
            //3、请求支付宝进行付款，并获取支付结果
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = client.sdkExecute(alipayRequest);
            String result = response.getBody();
            //返回付款信息
            return toSuccessResult(result,"获取参数成功");
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return toFailMsg("请求获取出错");
        }
    }

    /**
     * 退款
     * @param out_trade_no  交易流水号
     * @param refund_amount  金额
     * @param reason  退款原因
     * @return
     */
    public static Map<String,Object> orderRefund(String out_trade_no, String refund_amount,String reason) {
        // 创建API对应的request类
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel bizModel = new AlipayTradeRefundModel();
        bizModel.setOutTradeNo(out_trade_no);
        bizModel.setRefundAmount(refund_amount);
        bizModel.setRefundReason(reason);
        bizModel.setOutRequestNo(System.currentTimeMillis()+"");
        request.setBizModel(bizModel);
        try {
            // 通过alipayClient调用API，获得对应的response类
            AlipayTradeRefundResponse response = client.execute(request);
            String result = response.getBody();
            return toSuccessResult(result,"获取参数成功");
        } catch (Exception e) {
            e.printStackTrace();
            return toFailMsg("请求获取出错");
        }
    }

    /*返回支付宝服务*/
    public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg
                + "]]></return_msg></xml>";
    }

    /**
     * 操作失败返回理由
     */
    public static Map<String,Object> toFailMsg(String msg){
        Map<String,Object> map=new HashMap<>();
        map.put("code", 1);
        map.put("msg",msg);
        return map;
    }

    /**
     * 操作成功携带数据返回
     */
    public static Map<String, Object> toSuccessResult(Object object,String msg) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", msg);
        map.put("data", object);
        return map;
    }


    /**

     * 将url参数转换成map

     *

     * @param param aa=11&bb=22&cc=33

     * @return

     */

    public static Map<String, Object> getUrlParams(String param) {
        Map<String, Object> map = new HashMap<String, Object>(0);

        String[] params = param.split("&");

        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");

            if (p.length == 2) {
                map.put(p[0], p[1]);

            }

        }
        return map;
    }


}
